﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace LINQPadLogParser
{
  internal sealed class W3CLogEnumerable : ISiteLog
  {
    private readonly string _path;
    private readonly Uri _uri;
    private DateTime _from = DateTime.MinValue;
    private DateTime _to = DateTime.MaxValue;

    public W3CLogEnumerable(string path, Uri uri)
    {
      _path = path;
      _uri = uri;
    }

    public IEnumerator<W3CLogLine> GetEnumerator()
    {
      MultipleLineManager manager;
      if (LogParserDataContext.LineManager != null)
      {
        if (LogParserDataContext.LineManager.Path != _path)
          throw new NotSupportedException("Only one log source is supported!");
        manager = LogParserDataContext.LineManager;
      }
      else
      {
        LogParserDataContext.LineManager = manager = new MultipleLineManager(_path, _uri, _from, _to);
      }
      return manager.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }

    public IEnumerable<W3CLogLine> Slice(DateTime @from, DateTime to)
    {
      var result = (W3CLogEnumerable) MemberwiseClone();
      result._from = from;
      result._to = to;
      return result;
    }

    public IEnumerable<W3CLogLine> Slice(DateTime @from)
    {
      return Slice(from, DateTime.MaxValue);
    }

    public IEnumerable<W3CLogLine> Slice(TimeSpan time)
    {
      DateTime now = DateTime.Now;
      return Slice(now - time, now);
    }
  }
}